<template>
  <div class="admin-activity-container">
    <div class="page-header">
      <el-button @click="drawer = true" type="primary" icon="el-icon-plus">
        添加优惠券
      </el-button>
    </div>

    <!-- 优惠券列表卡片 -->
    <div class="coupon-list-card">
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-input
          placeholder="搜索优惠券名称"
          v-model="searchKeyword"
          class="search-input"
          clearable
          prefix-icon="el-icon-search"
        ></el-input>
        <el-select v-model="typeFilter" placeholder="类型筛选" clearable class="filter-select">
          <el-option label="全部类型" value=""></el-option>
          <el-option label="固定金额" value="FIXED"></el-option>
          <el-option label="百分比折扣" value="PERCENT"></el-option>
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态筛选" clearable class="filter-select">
          <el-option label="全部状态" value=""></el-option>
          <el-option label="未开始" value="NOT_STARTED"></el-option>
          <el-option label="进行中" value="ACTIVE"></el-option>
          <el-option label="已过期" value="EXPIRED"></el-option>
        </el-select>
      </div>

      <!-- 优惠券列表 -->
      <el-table 
        :data="filteredCoupons" 
        style="width: 100%"
        border
        stripe
        v-loading="loading"
        element-loading-text="加载中..."
        highlight-current-row
      >
        <el-table-column prop="name" label="名称" min-width="120"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="type" label="类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === 'FIXED' ? 'primary' : 'success'">
              {{ scope.row.type === 'FIXED' ? '固定金额' : '百分比折扣' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="面值" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 'FIXED'">¥{{ scope.row.value }}</span>
            <span v-else>{{ scope.row.value }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="minOrderAmount" label="最小订单金额" width="120">
          <template slot-scope="scope">
            <span>¥{{ scope.row.minOrderAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="maxDiscount" label="最大可减免" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.maxDiscount">¥{{ scope.row.maxDiscount }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期" width="240">
          <template slot-scope="scope">
            <div>{{ formatDate(scope.row.validFrom) }}</div>
            <div>至</div>
            <div>{{ formatDate(scope.row.validUntil) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getCouponStatusType(scope.row)">
              {{ getCouponStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="usageLimit" label="使用次数限制" width="120"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="small" 
              icon="el-icon-edit"
              @click="editCoupon(scope.row)">
              编辑
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              class="danger-text" 
              icon="el-icon-delete"
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalCoupons">
        </el-pagination>
      </div>
    </div>

    <!-- 添加/编辑优惠券抽屉 -->
    <el-drawer 
      :title="isEdit ? '编辑优惠券' : '添加优惠券'" 
      :visible.sync="drawer" 
      direction="rtl" 
      size="500px"
      :destroy-on-close="true"
      custom-class="coupon-drawer"
    >
      <div class="drawer-content">
        <div class="drawer-header">
          <h3>{{ isEdit ? '编辑优惠券信息' : '新增优惠券' }}</h3>
        </div>
        <!-- 添加优惠券表单 -->
        <el-form 
          :model="couponForm" 
          status-icon 
          :rules="rules" 
          ref="couponForm" 
          label-width="140px"
          class="coupon-form"
        >
          <el-form-item label="优惠券名称" prop="name">
            <el-input v-model="couponForm.name" placeholder="请输入优惠券名称"></el-input>
          </el-form-item>
          <el-form-item label="优惠券描述" prop="description">
            <el-input 
              type="textarea" 
              v-model="couponForm.description" 
              placeholder="请输入优惠券描述"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="优惠券类型" prop="type">
            <el-select v-model="couponForm.type" placeholder="请选择优惠券类型" style="width: 100%">
              <el-option label="固定金额" value="FIXED"></el-option>
              <el-option label="百分比折扣" value="PERCENT"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="couponForm.type === 'FIXED' ? '优惠金额' : '折扣比例'" prop="value">
            <el-input-number 
              v-model="couponForm.value" 
              :precision="2" 
              :step="0.1"
              :min="0"
              style="width: 100%"
              :placeholder="couponForm.type === 'FIXED' ? '请输入优惠金额' : '请输入折扣比例'"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="最小订单金额" prop="minOrderAmount">
            <el-input-number 
              v-model="couponForm.minOrderAmount" 
              :precision="2"
              :step="0.1"
              :min="0"
              style="width: 100%"
              placeholder="请输入最小订单金额"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="最大可减免金额" prop="maxDiscount">
            <el-input-number 
              v-model="couponForm.maxDiscount" 
              :precision="2" 
              :step="0.1"
              :min="0"
              style="width: 100%"
              placeholder="请输入最大可减免金额"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="有效期" required>
            <el-col :span="11">
              <el-form-item prop="validFrom">
                <el-date-picker
                  v-model="couponForm.validFrom"
                  type="datetime"
                  placeholder="开始日期"
                  style="width: 100%"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="validUntil">
                <el-date-picker
                  v-model="couponForm.validUntil"
                  type="datetime"
                  placeholder="结束日期"
                  style="width: 100%"
                  value-format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="使用次数限制" prop="usageLimit">
            <el-input-number 
              v-model="couponForm.usageLimit"
              :min="0"
              style="width: 100%"
              placeholder="请输入使用次数限制"
            ></el-input-number>
          </el-form-item>
          <el-form-item class="form-buttons">
            <el-button type="primary" @click="submitForm('couponForm')" :loading="submitLoading">{{ isEdit ? '保存' : '创建' }}</el-button>
            <el-button @click="resetForm('couponForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定要删除此优惠券吗？此操作不可逆。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      drawer: false,
      isEdit: false, // 是否为编辑模式
      currentPage: 1,
      pageSize: 10,
      loading: false,
      submitLoading: false,
      searchKeyword: '',
      typeFilter: '',
      statusFilter: '',
      deleteDialogVisible: false,
      currentDeleteCoupon: null,
      couponForm: {
        name: '',
        description: '',
        type: '',
        value: null,
        minOrderAmount: null,
        maxDiscount: null,
        validFrom: null,
        validUntil: null,
        usageLimit: null
      },
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择优惠券类型', trigger: 'change' }
        ],
        value: [
          { required: true, message: '请输入优惠券面值', trigger: 'blur' }
        ],
        minOrderAmount: [
          { required: true, message: '请输入最小订单金额', trigger: 'blur' }
        ],
        validFrom: [
          { required: true, message: '请选择有效期开始时间', trigger: 'change' }
        ],
        validUntil: [
          { required: true, message: '请选择有效期结束时间', trigger: 'change' }
        ],
        usageLimit: [
          { required: true, message: '请输入使用次数限制', trigger: 'blur' }
        ]
      },
      couponsList: []
    };
  },
  computed: {
    totalCoupons() {
      return this.couponsList.length;
    },
    filteredCoupons() {
      let result = [...this.couponsList];
      
      // 搜索关键字过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(coupon => 
          coupon.name.toLowerCase().includes(keyword) || 
          (coupon.description && coupon.description.toLowerCase().includes(keyword))
        );
      }
      
      // 类型过滤
      if (this.typeFilter) {
        result = result.filter(coupon => coupon.type === this.typeFilter);
      }
      
      // 状态过滤
      if (this.statusFilter) {
        const now = new Date();
        
        if (this.statusFilter === 'NOT_STARTED') {
          result = result.filter(coupon => new Date(coupon.validFrom) > now);
        } else if (this.statusFilter === 'ACTIVE') {
          result = result.filter(coupon => 
            new Date(coupon.validFrom) <= now && 
            new Date(coupon.validUntil) >= now
          );
        } else if (this.statusFilter === 'EXPIRED') {
          result = result.filter(coupon => new Date(coupon.validUntil) < now);
        }
      }
      
      // 分页
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return result.slice(startIndex, endIndex);
    }
  },
  methods: {
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          this.request.post('/coupons', this.couponForm)
            .then(response => {
              console.log('Coupon added:', response.data);
              this.$message.success(this.isEdit ? '优惠券更新成功' : '优惠券添加成功');
              this.getCouponsList();
              this.drawer = false;
              this.resetForm(formName);
            })
            .catch(error => {
              console.error('Failed to add coupon:', error);
              this.$message.error('操作失败，请重试');
            })
            .finally(() => {
              this.submitLoading = false;
            });
        } else {
          console.log('Error submitting form');
          return false;
        }
      });
    },
    
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.isEdit = false;
      this.couponForm = {
        name: '',
        description: '',
        type: '',
        value: null,
        minOrderAmount: null,
        maxDiscount: null,
        validFrom: null,
        validUntil: null,
        usageLimit: null
      };
    },
    
    // 获取优惠券列表
    getCouponsList() {
      this.loading = true;
      this.request.get('/coupons')
        .then(response => {
          this.couponsList = response.data;
        })
        .catch(error => {
          console.error('Failed to fetch coupons list:', error);
          this.$message.error('获取优惠券列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 日期格式化
    formatDate(date) {
      if (!date) return '--';
      const formatDate = new Date(date);
      return `${formatDate.getFullYear()}-${String(formatDate.getMonth() + 1).padStart(2, '0')}-${String(formatDate.getDate()).padStart(2, '0')} ${String(formatDate.getHours()).padStart(2, '0')}:${String(formatDate.getMinutes()).padStart(2, '0')}`;
    },
    
    // 获取优惠券状态文本
    getCouponStatusText(coupon) {
      const now = new Date();
      const startDate = new Date(coupon.validFrom);
      const endDate = new Date(coupon.validUntil);
      
      if (startDate > now) {
        return '未开始';
      } else if (endDate < now) {
        return '已过期';
      } else {
        return '进行中';
      }
    },
    
    // 获取优惠券状态类型
    getCouponStatusType(coupon) {
      const now = new Date();
      const startDate = new Date(coupon.validFrom);
      const endDate = new Date(coupon.validUntil);
      
      if (startDate > now) {
        return 'info';
      } else if (endDate < now) {
        return 'danger';
      } else {
        return 'success';
      }
    },
    
    // 编辑优惠券
    editCoupon(coupon) {
      this.isEdit = true;
      this.couponForm = { ...coupon };
      this.drawer = true;
    },
    
    // 处理删除
    handleDelete(coupon) {
      this.currentDeleteCoupon = coupon;
      this.deleteDialogVisible = true;
    },
    
    // 确认删除
    confirmDelete() {
      if (!this.currentDeleteCoupon) return;
      
      // 这里应该是删除的API调用，根据实际后端接口调整
      console.log('删除优惠券:', this.currentDeleteCoupon);
      this.$message.success('删除成功');
      this.getCouponsList();
      this.deleteDialogVisible = false;
      this.currentDeleteCoupon = null;
    },
    
    // 分页处理
    handleCurrentChange(val) {
      this.currentPage = val;
    }
  },
  created() {
    this.getCouponsList();
  }
};
</script>

<style scoped>
.admin-activity-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.coupon-list-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.filter-container {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
  margin-right: 15px;
  margin-bottom: 10px;
}

.filter-select {
  width: 150px;
  margin-right: 15px;
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.drawer-content {
  padding: 20px;
}

.drawer-header {
  margin-bottom: 20px;
}

.drawer-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.coupon-form {
  padding: 0 10px;
}

.form-buttons {
  margin-top: 30px;
  text-align: right;
}

.danger-text {
  color: #F56C6C;
}

::v-deep .coupon-drawer .el-drawer__header {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #e6e6e6;
  font-size: 18px;
  font-weight: bold;
}

::v-deep .el-table {
  margin-bottom: 20px;
}

::v-deep .el-table .cell {
  padding: 10px 12px;
}

::v-deep .el-form-item__label {
  font-weight: 500;
}

::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>